import { RectNodeModel } from '@logicflow/core'

class CustomLfModel extends RectNodeModel {
  initNodeData(data: any) {
    super.initNodeData(data)
    this.width = 240
    this.height = data.properties?.height || 380
  }

  getDefaultAnchor() {
    const { width, height, x, y, id, properties } = this
    const anchors = []

    // 左侧锚点（固定一个）
    anchors.push({
      x: x - width / 2,
      y: y,
      name: 'left',
      id: `${id}_0`,
      edgeAddable: false // 只能作为终点，不可作为起点
    })

    // 根据实际Vue组件结构精确计算
    const hasElseBranch = properties?.if_else_matching && properties.if_else_matching.length > 0
    const rightAnchorCount = hasElseBranch ? 3 : 2

    // 使用相对位置的方式，更简单准确
    const nodeTop = y - height / 2
    const nodeBottom = y + height / 2

    // 将节点内容区域分成几个部分
    // 头部占约30%，剩余70%给三个盒子
    const headerRatio = 0.25 // 头部占25%
    const contentRatio = 0.75 // 内容占75%

    const headerHeight = height * headerRatio
    const contentHeight = height * contentRatio
    const contentTop = nodeTop + headerHeight

    if (rightAnchorCount === 2) {
      // 只有IF和ELSE两个锚点
      // IF占内容区域的前60%，ELSE占后40%
      const ifRatio = 0.6
      const elseRatio = 0.4

      const ifCenter = contentTop + contentHeight * ifRatio * 0.5
      const elseCenter = contentTop + contentHeight * ifRatio + contentHeight * elseRatio * 0.5

      anchors.push({
        x: x + width / 2,
        y: ifCenter,
        name: 'if',
        id: `${id}_1`
      })

      anchors.push({
        x: x + width / 2,
        y: elseCenter,
        name: 'else',
        id: `${id}_2`
      })
    } else if (rightAnchorCount === 3) {
      // 有IF、ELSE-IF、ELSE三个锚点
      // 根据实际条件项数量动态分配比例
      const ifItemCount = properties?.if_matching?.length || 1
      const elseIfItemCount = properties?.if_else_matching?.length || 1

      // 基础高度 + 动态高度
      const baseHeight = 60 // 每个盒子的基础高度（标题+按钮+padding）
      const itemHeight = 42 // 每个条件项的高度

      const ifBoxHeight = baseHeight + ifItemCount * itemHeight
      const elseIfBoxHeight = baseHeight + elseIfItemCount * itemHeight
      const elseBoxHeight = 40 // ELSE盒子固定高度

      const totalBoxHeight = ifBoxHeight + elseIfBoxHeight + elseBoxHeight

      // 计算各盒子在内容区域中的相对位置
      let currentPos = 0

      // IF盒子中心
      const ifCenter =
        contentTop + (currentPos + ifBoxHeight / 2) * (contentHeight / totalBoxHeight)
      currentPos += ifBoxHeight

      // ELSE-IF盒子中心
      const elseIfCenter =
        contentTop + (currentPos + elseIfBoxHeight / 2) * (contentHeight / totalBoxHeight)
      currentPos += elseIfBoxHeight

      // ELSE盒子中心
      const elseCenter =
        contentTop + (currentPos + elseBoxHeight / 2) * (contentHeight / totalBoxHeight) - 30

      anchors.push({
        x: x + width / 2,
        y: ifCenter,
        name: 'if',
        id: `${id}_1`
      })

      anchors.push({
        x: x + width / 2,
        y: elseIfCenter,
        name: 'elseif',
        id: `${id}_2`
      })

      anchors.push({
        x: x + width / 2,
        y: elseCenter,
        name: 'else',
        id: `${id}_3`
      })
    }

    return anchors
  }

  // 当属性更新时，重新计算锚点并更新连线
  updateData(nodeData: any) {
    super.updateData(nodeData)

    // 高度更新后，锚点会自动重新计算
    if (nodeData.properties?.height) {
      this.height = nodeData.properties.height

      // 延迟更新连线位置，确保DOM已更新
      setTimeout(() => {
        this.updateConnectedEdges()
      }, 50)
    }
  }

  // 更新连接到此节点的边的位置
  updateConnectedEdges() {
    const lf = this.graphModel?.lf
    if (!lf) return

    const connectedEdges = lf.getNodeEdges(this.id)
    const newAnchors = this.getDefaultAnchor()
    const rightAnchors = newAnchors.filter(
      (anchor) => anchor.name === 'if' || anchor.name === 'elseif' || anchor.name === 'else'
    )

    connectedEdges.forEach((edge) => {
      // 只更新从此节点出发的边
      if (edge.sourceNodeId === this.id) {
        const anchorName = this.getAnchorNameFromId(edge.sourceAnchorId)
        const newAnchor = rightAnchors.find((anchor) => anchor.name === anchorName)

        if (newAnchor) {
          // 更新边的起始点
          const edgeModel = lf.getEdgeModelById(edge.id)
          if (edgeModel) {
            edgeModel.updateStartPoint({
              x: newAnchor.x,
              y: newAnchor.y
            })

            // 更新pointsList第一个点
            if (edgeModel.pointsList && edgeModel.pointsList.length > 0) {
              edgeModel.pointsList[0] = {
                x: newAnchor.x,
                y: newAnchor.y
              }
            }

            // 更新文本位置
            if (edgeModel.text) {
              edgeModel.text.x = (edgeModel.startPoint.x + edgeModel.endPoint.x) / 2
              edgeModel.text.y = (edgeModel.startPoint.y + edgeModel.endPoint.y) / 2
            }
          }
        }
      }
    })

    // 强制重新渲染
    if (lf.graphModel) {
      lf.graphModel.eventCenter.emit('graph:updated')
    }
  }

  // 从锚点ID获取锚点名称
  getAnchorNameFromId(anchorId: string): string {
    if (anchorId.includes('_1')) return 'if'
    if (anchorId.includes('_2')) {
      // 需要判断是elseif还是else
      const hasElseBranch =
        this.properties?.if_else_matching && this.properties.if_else_matching.length > 0
      return hasElseBranch ? 'elseif' : 'else'
    }
    if (anchorId.includes('_3')) return 'else'
    return 'if' // 默认
  }

  // 重写setProperties方法，确保锚点更新
  setProperties(properties: any) {
    super.setProperties(properties)

    // 当if_matching或if_else_matching变化时，重新计算锚点
    if (properties.if_matching || properties.if_else_matching) {
      setTimeout(() => {
        this.updateConnectedEdges()
      }, 100)
    }
  }
}

export default CustomLfModel
